/**
 * 商品 - 新建或编辑界面
 */
Ext.define("PSI.Goods.GoodsEditForm", {
	extend : "Ext.window.Window",

	config : {
		parentForm : null,
		entity : null
	},

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;
		var entity = me.getEntity();

		Ext.define("PSIGoodsUnit", {
					extend : "Ext.data.Model",
					fields : ["id", "name"]
				});

		var unitStore = Ext.create("Ext.data.Store", {
					model : "PSIGoodsUnit",
					autoLoad : false,
					data : []
				});
		me.unitStore = unitStore;

		me.adding = entity == null;

		var buttons = [];
		if (!entity) {
			buttons.push({
						text : "保存并继续新增",
						formBind : true,
						handler : function() {
							me.onOK(true);
						},
						scope : me
					});
		}

		buttons.push({
					text : "保存",
					formBind : true,
					iconCls : "PSI-button-ok",
					handler : function() {
						me.onOK(false);
					},
					scope : me
				}, {
					text : entity == null ? "关闭" : "取消",
					handler : function() {
						me.close();
					},
					scope : me
				});

		var selectedCategory = me.getParentForm().getCategoryGrid()
				.getSelectionModel().getSelection();
		var defaultCategoryId = null;
		if (selectedCategory != null && selectedCategory.length > 0) {
			defaultCategoryId = selectedCategory[0].get("id");
		}

		Ext.apply(me, {
			title : entity == null ? "新增商品" : "编辑商品",
			modal : true,
			resizable : false,
			onEsc : Ext.emptyFn,
			width : 480,
			height : 400,
			layout : "border",
			items : [{
						region : "south",
						layout : "fit",
						height : 120,
						border : 0,
						items : [me.getBarcodeGrid()]
					}, {
						region : "center",
						layout : "fit",
						border : 0,
						items : [{
							border : 0,
							id : "editForm",
							xtype : "form",
							layout : {
								type : "table",
								columns : 2
							},
							height : "100%",
							bodyPadding : 5,
							defaultType : 'textfield',
							fieldDefaults : {
								labelWidth : 60,
								labelAlign : "right",
								labelSeparator : "",
								msgTarget : 'side'
							},
							items : [{
								xtype : "hidden",
								name : "id",
								value : entity == null ? null : entity
										.get("id")
							}, {
								id : "editCategory",
								xtype : "psi_goodscategoryfield",
								fieldLabel : "商品分类",
								allowBlank : false,
								blankText : "没有输入商品分类",
								beforeLabelTextTpl : PSI.Const.REQUIRED,
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								id : "editCategoryId",
								name : "categoryId",
								xtype : "hidden",
								value : defaultCategoryId
							}, {
								id : "editCode",
								fieldLabel : "商品编码",
								allowBlank : false,
								blankText : "没有输入商品编码",
								beforeLabelTextTpl : PSI.Const.REQUIRED,
								name : "code",
								value : entity == null ? null : entity
										.get("code"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								id : "editName",
								fieldLabel : "品名",
								colspan : 2,
								width : 430,
								allowBlank : false,
								blankText : "没有输入品名",
								beforeLabelTextTpl : PSI.Const.REQUIRED,
								name : "name",
								value : entity == null ? null : entity
										.get("name"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								id : "editSpec",
								fieldLabel : "规格型号",
								colspan : 2,
								width : 430,
								name : "spec",
								value : entity == null ? null : entity
										.get("spec"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								xtype : "fieldcontainer",
								fieldLabel : "计量单位",
								layout : "hbox",
								width : 210,
								items : [{
											id : "editUnit",
											xtype : "combo",
											// fieldLabel : "计量单位",
											allowBlank : false,
											blankText : "没有输入计量单位",
											beforeLabelTextTpl : PSI.Const.REQUIRED,
											valueField : "id",
											displayField : "name",
											store : unitStore,
											queryMode : "local",
											editable : false,
											name : "unitId",
											listeners : {
												specialkey : {
													fn : me.onEditSpecialKey,
													scope : me
												}
											},
											width : 100
										}, {
											xtype : "button",
											iconCls : "PSI-button-add",
											width : 26,
											handler : me.onAddUnit,
											scope : me
										}]
							}, {
								id : "editPackageCount",
								fieldLabel : "装箱数",
								xtype : "numberfield",
								hideTrigger : true,
								allowDecimals : false,
								name : "packageCount",
								value : entity == null ? null : entity
										.get("packageCount"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								id : "editBarCode",
								name : "barCode",
								xtype : "hidden"
							}, {
								id : "editBrandId",
								xtype : "hidden",
								name : "brandId"
							}, {
								id : "editBrand",
								fieldLabel : "品牌",
								name : "brandName",
								xtype : "PSI_goods_brand_ext_field",
								showAddButton : true,
								colspan : 2,
								width : 430,
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								fieldLabel : "销售价",
								xtype : "numberfield",
								hideTrigger : true,
								name : "salePrice",
								id : "editSalePrice",
								value : entity == null ? null : entity
										.get("salePrice"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								fieldLabel : "平均采购价",
								xtype : "numberfield",
								labelWidth : 80,
								width : 210,
								hideTrigger : true,
								name : "purchasePrice",
								id : "editPurchasePrice",
								value : entity == null ? null : entity
										.get("purchasePrice"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								}
							}, {
								fieldLabel : "重量(KG)",
								name : "weight",
								xtype : "numberfield",
								hideTrigger : true,
								id : "editWeight",
								value : entity == null ? null : entity
										.get("weight"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								},
								colspan : 1
							}, {
								xtype : 'fieldcontainer',
								fieldLabel : '保质期管理',
								labelWidth : 80,
								defaultType : 'radiofield',
								colspan : 1,
								width : 200,
								defaults : {
									flex : 1
								},
								layout : 'hbox',
								items : [{
											boxLabel : '启用',
											name : 'useQC',
											inputValue : '1',
											id : 'radioUseQC'
										}, {
											boxLabel : '停用',
											name : 'useQC',
											inputValue : '0',
											id : 'radioStopQC'
										}]
							}, {
								fieldLabel : "备注",
								name : "memo",
								id : "editMemo",
								value : entity == null ? null : entity
										.get("memo"),
								listeners : {
									specialkey : {
										fn : me.onLastEditSpecialKey,
										scope : me
									}
								},
								colspan : 2,
								width : 430
							}]
						}]
					}],
			buttons : buttons,
			listeners : {
				show : {
					fn : me.onWndShow,
					scope : me
				},
				close : {
					fn : me.onWndClose,
					scope : me
				}
			}
		});

		me.callParent(arguments);

		me.__editorList = ["editCategory", "editCode", "editName", "editSpec",
				"editUnit", "editPackageCount", "editBrand", "editSalePrice",
				"editPurchasePrice", "editWeight", "editMemo"];
	},

	onWndShow : function() {
		var me = this;
		var editCode = Ext.getCmp("editCode");
		editCode.focus();
		editCode.setValue(editCode.getValue());

		var categoryId = Ext.getCmp("editCategoryId").getValue();
		var el = me.getEl();
		var unitStore = me.unitStore;
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL + "Home/Goods/goodsInfo",
					params : {
						id : me.adding ? null : me.getEntity().get("id"),
						categoryId : categoryId
					},
					method : "POST",
					callback : function(options, success, response) {
						unitStore.removeAll();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);
							if (data.units) {
								unitStore.add(data.units);
							}

							if (!me.adding) {
								// 编辑商品信息
								Ext.getCmp("editCategory")
										.setIdValue(data.categoryId);
								Ext.getCmp("editCategory")
										.setValue(data.categoryName);
								Ext.getCmp("editCode").setValue(data.code);
								Ext.getCmp("editName").setValue(data.name);
								Ext.getCmp("editSpec").setValue(data.spec);
								Ext.getCmp("editUnit").setValue(data.unitId);
								Ext.getCmp("editSalePrice")
										.setValue(data.salePrice);
								Ext.getCmp("editPurchasePrice")
										.setValue(data.purchasePrice);
								Ext.getCmp("editMemo").setValue(data.memo);
								var brandId = data.brandId;
								if (brandId) {
									var editBrand = Ext.getCmp("editBrand");
									editBrand.setIdValue(brandId);
									editBrand.setValue(data.brandFullName);
								}

								Ext.getCmp("editWeight").setValue(data.weight);
								Ext.getCmp("radioUseQC").setValue(data.useQC);
								Ext.getCmp("radioStopQC").setValue(!data.useQC);
								Ext.getCmp("editPackageCount")
										.setValue(data.packageCount);

								if (data.barcodeList) {
									var store = me.getBarcodeGrid().getStore();
									store.removeAll();
									store.add(data.barcodeList);
									if (store.getCount() == 0) {
										store.add({});
									}
								}
							} else {
								// 新增商品
								if (unitStore.getCount() > 0) {
									var unitId = unitStore.getAt(0).get("id");
									Ext.getCmp("editUnit").setValue(unitId);
								}
								if (data.categoryId) {
									Ext.getCmp("editCategory")
											.setIdValue(data.categoryId);
									Ext.getCmp("editCategory")
											.setValue(data.categoryName);
								}

								me.getBarcodeGrid().getStore().add({});
							}
						}

						el.unmask();
					}
				});
	},

	onOK : function(thenAdd) {
		var me = this;

		// 条码
		var store = me.getBarcodeGrid().getStore();
		var idList = [];
		for (var i = 0; i < store.getCount(); i++) {
			idList.push(store.getAt(i).get("id"));
		}
		Ext.getCmp("editBarCode").setValue(idList.join(","));

		var useQC = Ext.getCmp("radioUseQC").getValue();
		var stopQC = Ext.getCmp("radioStopQC").getValue();
		// 新增商品的时候，判断是否设置过数据
		if (useQC == stopQC) {
			PSI.MsgBox.showInfo("没有设置保质期管理");
			return;
		}

		var categoryId = Ext.getCmp("editCategory").getIdValue();
		if (!categoryId) {
			PSi.MsgBox.showInfo("没有选择商品分类");
			return;
		}
		Ext.getCmp("editCategoryId").setValue(categoryId);

		var brandId = Ext.getCmp("editBrand").getIdValue();
		Ext.getCmp("editBrandId").setValue(brandId);

		var code = Ext.getCmp("editCode").getValue();
		if (!code) {
			PSI.MsgBox.showInfo("没有输入商品编码");
			return;
		}
		var name = Ext.getCmp("editName").getValue();
		if (!name) {
			PSI.MsgBox.showInfo("没有输入品名");
			return;
		}

		var f = Ext.getCmp("editForm");
		var el = me.getEl();
		el.mask(PSI.Const.SAVING);
		f.submit({
					url : PSI.Const.BASE_URL + "Home/Goods/editGoods",
					method : "POST",
					success : function(form, action) {
						el.unmask();
						me.__lastId = action.result.id;
						me.getParentForm().__lastId = me.__lastId;

						PSI.MsgBox.tip("数据保存成功");
						me.focus();

						if (thenAdd) {
							me.clearEdit();
						} else {
							me.close();
							me.getParentForm().freshGoodsGrid();
						}
					},
					failure : function(form, action) {
						el.unmask();
						PSI.MsgBox.showInfo(action.result.msg, function() {
									Ext.getCmp("editCode").focus();
								});
					}
				});
	},

	onEditSpecialKey : function(field, e) {
		if (e.getKey() === e.ENTER) {
			var me = this;
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i];
				if (id === editorId) {
					var edit = Ext.getCmp(me.__editorList[i + 1]);
					edit.focus();
					edit.setValue(edit.getValue());
				}
			}
		}
	},

	onLastEditSpecialKey : function(field, e) {
		if (e.getKey() == e.ENTER) {
			var f = Ext.getCmp("editForm");
			if (f.getForm().isValid()) {
				var me = this;
				me.onOK(me.adding);
			}
		}
	},

	clearEdit : function() {
		var me = this;

		Ext.getCmp("editCode").focus();

		var editors = [Ext.getCmp("editCode"), Ext.getCmp("editName"),
				Ext.getCmp("editSpec"), Ext.getCmp("editSalePrice"),
				Ext.getCmp("editPurchasePrice"), Ext.getCmp("editWeight"),
				Ext.getCmp("editPackageCount"), Ext.getCmp("editMemo")];
		for (var i = 0; i < editors.length; i++) {
			var edit = editors[i];
			edit.setValue(null);
			edit.clearInvalid();
		}

		me.getBarcodeGrid().getStore().removeAll();
	},

	onWndClose : function() {
		var me = this;
		me.getParentForm().__lastId = me.__lastId;
		me.getParentForm().freshGoodsGrid();
	},

	getBarcodeGrid : function() {
		var me = this;
		if (me.__barcodeGrid) {
			return me.__barcodeGrid;
		}

		var modelName = "PSIBarcode";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "barcode"]
				});

		me.__cellEditing = Ext.create("PSI.UX.CellEditing", {
					clicksToEdit : 1,
					listeners : {
						edit : {
							fn : me.cellEditingAfterEdit,
							scope : me
						}
					}
				});

		me.__barcodeGrid = Ext.create("Ext.grid.Panel", {
					margin : "0 30 5 30",
					viewConfig : {
						enableTextSelection : true
					},
					plugins : [me.__cellEditing],
					columnLines : true,
					columns : [{
								header : "条码",
								dataIndex : "barcode",
								menuDisabled : true,
								sortable : false,
								width : 320,
								editor : {
									xtype : "psi_barcodefield",
									parentCmp : me
								}
							}, {
								header : "",
								id : "columnActionDelete",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/delete.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.remove(store.getAt(row));
										if (store.getCount() == 0) {
											store.add({});
										}
									},
									scope : me
								}]
							}, {
								header : "",
								id : "columnActionAdd",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/add.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.insert(row, [{}]);
									},
									scope : me
								}]
							}],
					store : Ext.create("Ext.data.Store", {
								model : modelName,
								autoLoad : false,
								data : []
							})
				});

		return me.__barcodeGrid;
	},

	cellEditingAfterEdit : function(editor, e) {
		var me = this;
	},

	__setBarcodeInfo : function(data) {
		var me = this;
		var item = me.getBarcodeGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}
		var barcode = item[0];

		barcode.set("id", data.id);
		barcode.set("barcode", data.barcode);
	},

	onAddUnit : function() {
		var me = this;
		var form = Ext.create("PSI.Goods.UnitEditForm", {
					closeCallbackFunc : me.__afterAddUnit,
					closeCallbackScope : me
				});
		form.show();
	},

	__afterAddUnit : function(thisObj) {
		var me = thisObj;
		var el = me.getEl();
		var unitStore = me.unitStore;
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL + "Home/Goods/allUnits",
					params : {},
					method : "POST",
					callback : function(options, success, response) {
						unitStore.removeAll();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);
							unitStore.add(data);
						}

						el.unmask();
					}
				});
	}
});